package cn.apestar.common.dao.impl;

import cn.apestar.common.dao.JdbcTemplateDao;
import cn.apestar.common.persistence.Page;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JdbcTemplateDaoImpl extends JdbcDaoSupport implements JdbcTemplateDao {

    @Override
    public Page findPageSql(String sql, Object[] params, int currentPage, int pageSize) {

        int totalCount = countDataTotalBySQLPrepare(sql);
        List list = new ArrayList();
        int startRow = (currentPage - 1) * pageSize;
        if (startRow < 0) {
            startRow = 0;
        }
        sql = "SELECT a.* FROM (" + sql + ") a ";

        Object[] new_params = null;
        // 重新更新参数
        if (params == null) {
            new_params = new Object[2];
            new_params[0] = new Integer(startRow + 1);
            new_params[1] = new Integer(startRow + pageSize);

        } else {
            new_params = new Object[params.length + 2];
            for (int i = 0; i < params.length; i++) {
                new_params[i] = params[i];
            }
            new_params[params.length] = new Integer(startRow + 1);
            new_params[params.length + 1] = new Integer(startRow + pageSize);
        }

        sql = sql + "LIMIT " + startRow + " , " + pageSize;
        System.out.println(sql);
        if (totalCount > 0) {
            list = getJdbcTemplate().queryForList(sql);
        }
        return new Page(currentPage, pageSize, totalCount, list);
    }

    /**
     * 统计记录总数
     * @return 记录总数 2012-3-12 gavin lee 修改方法为保护类型的，允许子类能够覆盖这个方法，处理比较特殊的sql脚本查询
     */
    public int countDataTotalBySQLPrepare(String sql, Object... values) {
        int totalCount = 0;
        String lowerHql = sql.trim().toLowerCase();
        int fromPos = 0;
        int orderPos = lowerHql.length();
        fromPos = lowerHql.indexOf(" from ") + 1;
        orderPos = lowerHql.indexOf("order by ") + 1;

        String countSql;
        if (orderPos != 0)
            countSql = "select count(1) as num " + sql.substring(fromPos, orderPos - 1);
        else
            countSql = "select count(1) as num " + sql.substring(fromPos);

        int distinctPos = lowerHql.indexOf(" distinct ");

        totalCount = getJdbcTemplate().queryForObject(countSql,Integer.class);
        return totalCount;
    }

    @Override
    public Map findMapbySql(String sql) {
        return getJdbcTemplate().queryForMap(sql);
    }

    @Override
    public List findListbySql(String sql) {
        return getJdbcTemplate().queryForList(sql);
    }

    @Override
    public void uodateSQL(String sql, Object[] args) {
        this.getJdbcTemplate().update(sql, args);
    }

}
